﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    public static class DictionaryTool
    {
        public static Dictionary<Type,Component[]> GetAllComponent(GameObject go,bool isAdd)
        {
            var dict = new Dictionary<Type, Component[]>();
            var comps = go.GetComponents<Component>();
            foreach(var c in comps)
            {
                if (c == null) Debug.LogWarning("Missing script component in :" + go.name);
                else if(isAdd)
                {
                    Type t = c.GetType();
                    if (!dict.ContainsKey(t))
                    {
                        dict.Add(t, go.GetComponents(t));
                    }

                }
            }
            return dict;
        }

        public static bool IsExist(Transform root, GameObject go, out string path)
        {
            if (root.gameObject == go)
            {
                path = string.Empty;
                return true;
            }

            List<string> paths = new List<string>();
            for (int i = 0; i < root.childCount; i++)
            {
                var child = root.GetChild(i);
                if (Find(paths, child, go))
                {
                    path = "";
                    for(int j = 0; j < paths.Count; j++)
                    {
                        path += paths[j];
                        if (j != paths.Count - 1) path += "/";
                    }
                    return true;
                }

            }
            path = "";
            return false;

        }

        private static bool Find(List<string> list,Transform root,GameObject go)
        {
            list.Add(root.name);
            if (root.gameObject == go) return true;
            for(int i = 0; i < root.childCount; i++)
            {
                var child = root.GetChild(i);
                if (Find(list, child, go)) return true;

            }
            list.RemoveAt(list.Count - 1);
            return false;
        }

    }
}

